<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="order-head">
    <CommonHead title="我的全部订单"/>
  </header>

  <!--体: 订单列表-->
  <section class="order-body">

    <!--当前存在订单时展示-->
    <div v-if="orderDetails.length > 0">

      <van-divider dashed>订单列表</van-divider>

      <!--遍历订单数据-->
      <div v-for="orderDetail in orderDetails" :key="orderDetail['orderDetailId']">

        <van-divider content-position="left">
          <!--图标: 类型，颜色，尺寸，点击时触发-->
          <van-icon name="delete" color="red" size="15" @click="deleteOrder(orderDetail['orderId'])"/>
          <span>&nbsp;订单号: {{ orderDetail['orderNumber'] }}</span>
        </van-divider>

        <!--滑动单元格: 遍历订单数据-->
        <van-swipe-cell v-for="item in orderDetail['items']" :key="item['orderDetailId']">

          <!--卡片: 视频标题，视频价格，原始价格，视频描述，点击卡片时触发-->
          <van-card :title="item['video']['videoTitle'] + ' - ' + item['video']['author']"
                    :price="item['video']['price']"
                    :origin-price="item['video']['price'] / 0.8"
                    @click="playVideo(item['video']['videoId'])">

            <!--视频封面图: 计算MinIO地址，尺寸自适，高度-->
            <template #thumb>
              <van-image :src="minio(item['video']['coverImage'])" fit="fit" height="100%"/>
            </template>

            <!--视频封评分: 双绑视频评分，尺寸-->
            <template #tags>
              <van-rate v-model="item['video']['star']" size="12px"/>
            </template>

          </van-card>

          <!--按钮: 删除商品-->
          <template #right>
            <van-button square type="danger" text="删除" class="delete-order-btn"
                        @click="deleteOrderDetail(item['orderDetailId'])"/>
          </template>

        </van-swipe-cell>
      </div>

      <van-divider dashed/>

      <!--分页: 双绑当前第几页，左箭头，右箭头，使用省略号，总条目数，每页多少条，改变时触发-->
      <van-pagination v-model="orderPageInfo['pageNum']"
                      prev-text="<<" next-text=">>" force-ellipses
                      :total-items="orderPageInfo['total']"
                      :items-per-page="orderPageInfo['pageSize']"
                      @change="changePage"/>
    </div>

    <!--当前不存在订单时展示-->
    <div v-else>
      <van-divider>您暂未购买任何课程</van-divider>
    </div>

  </section>

  <!--脚: 引入 CommonFoot 子组件-->
  <footer class="order-foot">
    <CommonFoot/>
  </footer>

</template>

<script setup>

import CommonHead from "@/components/CommonHead";
import CommonFoot from "@/components/CommonFoot";
import {DELETE_ORDER, PAGE_ORDER_DETAIL, DELETE_ORDER_DETAIL} from "@/api/order";
import {MINIO_HOST, SUCCESS} from '@/constant';
import router from "@/router";
import {ref, computed, shallowReactive, onBeforeMount} from "vue";
import {useStore} from "vuex";
import {showFailToast, showSuccessToast} from "vant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();

// data: 用户主键
const userId = sessionStorage.getItem('userId');

// data: 订单明细列表
let orderDetails = ref([]);

// data: 订单明细列表分页数据
let orderPageInfo = shallowReactive({'total': 0, 'pageNum': 1, 'pageSize': 4});

/* ==================== computed ==================== */

// computed: 拼接MinIO视频封面目录前缀
const minio = computed(() => src => MINIO_HOST + "/cover/" + src);

/* ==================== method ==================== */

// method: 分页获取全部订单列表
async function pageOrderDetail(pageNum, pageSize) {

  // 异步调用获取当前用户所有订单列表的接口
  const result = await PAGE_ORDER_DETAIL(pageNum, pageSize);
  let resp = result['data'];
  if (resp.code === SUCCESS) {

    // 每次查询成功后，都先清空 [订单明细列表]，以免数据堆积
    orderDetails.value = [];

    // 获取响应数据
    let data = resp.data;

    // 订单明细列表分页数据
    orderPageInfo['pageNum'] = data['pageNum'];
    orderPageInfo['pageSize'] = data['pageSize'];
    orderPageInfo['total'] = data['total'];

    // 构造orderDetails数组数据: 赋值遍历所有订单明细表数据
    data['list'].forEach(orderDetail => {

      // 取出订单主键和订单编号
      let orderId = orderDetail['order']['orderId'];
      let orderNumber = orderDetail['order']['orderNumber'];

      // 设置内容项: 每个内容项中都包含包括一条video视频数据和中间表主键
      let items = {
        'video': orderDetail['video'],
        'orderDetailId': orderDetail['orderDetailId']
      }

      // 若当前orders数组为空，则直接向数组追加一条JSON数据
      if (orderDetails.value.length <= 0) {
        orderDetails.value.push({'orderId': orderId, 'orderNumber': orderNumber, 'items': [items]});
      }
      // 若当前orders数组不为空，则根据订单ID判断orders数组中是否已存在相同订单
      else {
        // 当orders数组中存在相同订单时，返回全部相同的订单数组，否则返回空数组
        let sameOrders = orderDetails.value.filter(order => order['orderId'] === orderId);
        // 若存在相同的订单，则合并item数据
        if (sameOrders.length > 0) {
          orderDetails.value[0]['items'].push(items);
        }
        // 当orders数组中不存在相同的订单时，追加该条JSON数据
        else {
          orderDetails.value.push({'orderId': orderId, 'orderNumber': orderNumber, 'items': [items]});
        }
      }
    })
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

// method: 删除某一条指定的商品
async function deleteOrderDetail(videoOrderId) {

  // 危险操作保护
  if (!confirm("即将删除指定商品，确定吗？")) {
    return false;
  }

  // 异步调用 [按订单明细表主键] 删除 [订单明细] 的接口
  const result = await DELETE_ORDER_DETAIL(videoOrderId);
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    showSuccessToast('视频删除成功');
    // 当删除成功后重新查询订单明细列表
    await pageOrderDetail(1, orderPageInfo['pageSize'])
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

// method: 删除指定订单中的全部商品
async function deleteOrder(orderId) {

  // 危险操作保护
  if (!confirm("即将删除相同订单中的全部商品，确定吗？")) {
    return false;
  }

  // 异步调用接口: 按 [订单表主键] 删除一条 [订单]
  const result = await DELETE_ORDER(orderId);
  let resp = result['data'];
  if (resp.code === SUCCESS) {
    showSuccessToast('订单删除成功')
    // 当删除成功后重新查询订单列表
    await pageOrderDetail(1, orderPageInfo['pageSize'])
  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

// method: 播放视频
function playVideo(videoId) {
  router.push({'path': '/PlayVideo', 'query': {'videoId': videoId}});
}

// method: 当前显示第几页被改变时触发
function changePage(pageNum) {
  orderPageInfo['pageNum'] = pageNum;
  pageOrderDetail(pageNum, orderPageInfo['pageSize']);
}

/* ==================== beforeMount ==================== */

// beforeMount: DOM挂载前，判断用户是否登录
onBeforeMount(() => {
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
  } else {
    // 分页查询订单列表
    pageOrderDetail(1, orderPageInfo['pageSize']);
  }
});

</script>

<style scoped lang="scss">

.order-body {

  text-align: left; // 内容居左

  /*卡片中的图片*/
  .van-image {
    width: 130px; // 图片宽度
  }

  /**卡片中的文字内容: `:deep()` 用于深度修改框架组件的样式*/
  :deep(.van-card__content) {
    text-align: right; // 内容居右
  }

  /*滑动后出现的删除按钮*/
  .delete-order-btn {
    height: 100%; // 高度
  }
}

</style>